<template>
  <div ref="boxwrap" class="LiquidMedicine">
    <el-carousel direction="vertical" :autoplay="true" :height="chartStyle.height" :interval="interval">
      <el-carousel-item v-for="item in list" :key="item">
        <div :id="'type' + item" :width="chartStyle.width" :height="chartStyle.height" class="chart" />
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script>
import { cutLineName } from '@/utils'
import resize from '@/components/Charts/mixins/resize'
import { getLiquidMedicine } from '@/api/screen'
export default ({
  name: 'LiquidMedicine',
  mixins: [resize],
  props: {
    width: {
      type: String,
      default: '150px'
    },
    height: {
      type: String,
      default: '150px'
    },
    isresize: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list: [],
      chart: null,
      chartStyle: {
        width: '100%',
        height: '100%'
      },
      legendShow: false,
      resData: null,
      color: ['rgba(89,224,1,1)', 'rgba(158,58,226,1)', 'rgba(222,27,27,1)', 'rgba(46,200,207,1)', 'rgba(108,80,243,1)', 'rgba(4,178,139,1)'],
      fontColor: '#bebebe',
      currentView: {},
      interval: 1000 * 5, // 药水分析轮播切换速度 10s
      liquidTimer: null,
      refreshInterval: 1000 * 60 * 2 // 数据刷新速度 2min 1000 * 60 * 2
    }
  },
  // computed: {
  //   ...mapGetters([
  //     'regionid',
  //     'lineId'
  //   ])
  // },
  watch: {
    width: {
      immediate: true,
      handler: function(newval, oldval) {
        this.width = newval
      },
      deep: true
    },
    height: {
      immediate: true,
      handler: function(newval, oldval) {
        this.height = newval
      },
      deep: true
    },
    isresize(newval, oldval) {
      this.movement = newval
      this.chart.resize()
    }
  },
  mounted() {
    this.getDomHeight()
    this.domResize()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null

    if (this.liquidTimer) {
      clearTimeout(this.liquidTimer)
      this.liquidTimer = null
    }
  },
  created() {
    this.getCurrentView()
    if (this.$route.path.indexOf('/screen') !== -1) {
      this.dataRefresh()
    }
  },
  methods: {
    getDomHeight() {
      this.chartStyle = {
        width: this.$refs.boxwrap.clientWidth + 'px',
        height: this.$refs.boxwrap.clientHeight + 'px'
      }
    },
    domResize() {
      const that = this
      const dom = this.$refs.boxwrap
      this.$erd.listenTo(dom, function(element) {
        var width = element.clientWidth + 'px'
        var height = element.clientHeight + 'px'
        that.chartStyle = {
          width,
          height
        }
      })
    },
    getCurrentView() {
      this.currentView = {
        regionid: this.$Cookies.get('currentReginid'),
        lineId: this.$Cookies.get('currentLineId')
      }
      this.getData()
    },
    getData() {
      this.list = []
      getLiquidMedicine(this.currentView).then(response => {
        this.resData = response.data

        Object.keys(this.resData).forEach((ite, idx) => {
          this.list.push(idx)
        })
      }).then(() => {
        const list = []
        for (const key in this.resData) {
          const temp = []
          for (const k in this.resData[key]) {
            temp.push({
              lineName: cutLineName(k),
              data: this.resData[key][k]
            })
          }
          list.push({
            mediName: key,
            data: temp
          })
        }
        for (let i = 0; i < list.length; i++) {
          const mediId = `type${i}`
          const dataArr = []
          const type = list[i] // 药水种类
          for (let j = 0; j < type.data.length; j++) {
            const temp = type.data[j].data
            const obj = {
              name: type.data[j].lineName
            }
            const timeArr = []
            const val = []
            const upperLimit = []
            const lowerLimit = []
            for (let k = 0; k < temp.length; k++) {
              timeArr.push(temp[k].time)
              val.push(temp[k].value)
              upperLimit.push(temp[k].upperLimit)
              lowerLimit.push(temp[k].lowerLimit)
            }
            obj['time'] = timeArr
            obj['value'] = val
            obj['upperLimit'] = upperLimit
            obj['lowerLimit'] = lowerLimit
            dataArr.push(obj)
          }
          this.initChart(mediId, type.mediName, dataArr)
        }
      })
    },
    initChart(id, mediName, dataArr) {
      const seriesData = []
      const legendData = []
      const colorObj = {
        // upper: ['red','#f240ba'],
        // lower: ['yellow','#ffc778'],
        upper: ['red', 'red'],
        lower: ['red', 'red']
      }
      const lineType = ['solid', 'dashed']

      function lw(mediName, linename) {
        return (mediName.indexOf('氢氧化钠') !== -1 && linename.indexOf('B') !== -1) ? 2 : 1
      }
      for (let i = 0; i < dataArr.length; i++) {
        const linewidth = lw(mediName, dataArr[i].name)
        legendData.push(dataArr[i].name)
        seriesData.push({
          type: 'line',
          name: dataArr[i].name,
          data: dataArr[i].value,
          smooth: true,
          // smoothMonotone: "x",
          showSymbol: false,
          symbol: 'circle',
          connectNulls: true,
          silent: true,
          itemStyle: {
            color: this.color[i]
          },
          lineStyle: {
            type: mediName.indexOf('比重') !== -1 ? lineType[i] : lineType[0],
            shadowColor: 'rgba(0, 0, 0, .3)',
            shadowBlur: 0,
            shadowOffsetY: 2,
            shadowOffsetX: 2
          }
        },
        {
          name: dataArr[i].name + '上限',
          data: dataArr[i].upperLimit,
          type: 'line',
          symbolSize: 0,
          symbol: 'circle',
          connectNulls: true,
          itemStyle: {
            color: mediName.indexOf('氢氧化钠') !== -1 ? colorObj.upper[i] : 'red'
          },
          lineStyle: {
            width: linewidth,
            type: 'dashed'
          }
        }, {
          name: dataArr[i].name + '下限',
          data: dataArr[i].lowerLimit,
          type: 'line',
          symbolSize: 0,
          symbol: 'circle',
          connectNulls: true,
          itemStyle: {
            color: mediName.indexOf('氢氧化钠') !== -1 ? colorObj.lower[i] : 'red'
          },
          lineStyle: {
            width: linewidth,
            type: 'dashed'
          }
        })
      }

      this.chart = this.$echarts.init(document.getElementById(id), 'jyt-dark')
      this.chart.setOption({
        color: this.color,
        grid: {
          top: '22%',
          left: '5%',
          right: '10%',
          bottom: '15%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          confine: true // 是否将 tooltip 框限制在图表的区域内
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          textStyle: {
            color: this.fontColor,
            align: 'right'
          },
          right: 0,
          top: 0,
          padding: 0,
          itemWidth: 15,
          itemHeight: 10,
          data: legendData
        },
        dataZoom: [
          {
            show: true,
            type: 'inside',
            startValue: dataArr[0].time.length - 30,
            endValue: dataArr[0].time.length
          },
          {
            show: true,
            startValue: dataArr[0].time.length - 30,
            endValue: dataArr[0].time.length,
            bottom: 10,
            height: 10
          }
        ],
        xAxis: {
          name: '时间',
          nameGap: 5,
          nameTextStyle: {
            color: this.fontColor
          },
          type: 'category',
          axisLabel: {
            color: this.fontColor
          },
          boundaryGap: false,
          data: dataArr[0].time
        },
        yAxis: {
          name: mediName,
          nameGap: 5,
          nameTextStyle: {
            color: this.fontColor,
            align: 'left'
          },
          margin: 15,
          type: 'value',
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255,255,255,0.1)'
            }
          },
          axisLine: {
            show: true
          },
          axisLabel: {
            show: true,
            color: this.fontColor,
            formatter: '{value}%'
          },
          axisTick: {
            show: false
          },
          min: 'dataMin',
          max: 'dataMax'
        },
        series: seriesData

      })
    },
    // 数据刷新
    dataRefresh() {
      if (this.liquidTimer) {
        clearTimeout(this.liquidTimer)
        this.liquidTimer = null
      }
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
      this.liquidTimer = setTimeout(() => {
        this.getData()
        this.dataRefresh()
      }, this.refreshInterval)
    }
  }
})
</script>

<style lang="scss">
.LiquidMedicine .chart{
  width: 100%;
  height: 100%;
}
</style>
